<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\KeywordTwo;
use App\Models\TeachingMaterial;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Traits\HasUploadedFile;

class KeywordTwoController extends AdminController
{
    use HasUploadedFile;
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::style(
            <<<CSS
        table {
            text-align: center;
        }
CSS
        );
        $user = Admin::user();
        if ($user->is_admin == -1) {
            $class = $user->keywordTwo()->getQuery();
            $two = new KeywordTwo($class);
        } else {
            $two = new KeywordTwo();
        }
        return Grid::make($two, function (Grid $grid) use ($user) {
            if ($user->is_admin == 1) {
                $grid->model()->with('mechanism');
            }
            $grid->column('id')->sortable();
            if ($user->is_admin == 1) {
                $grid->column('mechanism.name', '所属机构');
            }
            $grid->column('name');
            $grid->column('data', '相关单词')->display(function ($value) {
                if (!empty($value)) {
                    $data = json_decode($value, true);
                    return array_column($data, 'key');
                }
                return '无';
            })->label();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('book_id', '所属教材')
                    ->select(TeachingMaterial::where('mechanism_id', Admin::user()->id)
                        ->pluck('name', 'id')->toArray())
                    ->width(3)->load('unit_id', 'books/select');
                $filter->equal('unit_id', '所属单元')->select()->width(3);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new KeywordTwo(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('data');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $user = Admin::user();
        return Form::make(new KeywordTwo(), function (Form $form) use ($user) {
            $form->display('id');
            if ($user->is_admin == 1) {
                $form->select('mechanism_id', '所属机构')
                    ->options(Administrator::where('is_admin', -1)
                        ->pluck('name', 'id')->toArray());
            }
            $form->text('name');
            if (Admin::user()->is_admin == -1) {
                $form->hidden('mechanism_id')->default(Admin::user()->id);
            }
            $form->table('data', function (NestedForm $table) {
                $table->text('key', '文案');
                $table->image('pic', '图片')
                    ->autoUpload()
                    ->accept('jpg,png,jpeg', 'image/*')
                    ->url('ones/files');
                $table->file('audio', '音频')
                    ->url('ones/files')
                    ->autoUpload();
            })->saving(function ($value) {
                return json_encode($value);
            });
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    public function handle()
    {
        $disk = $this->disk('admin');

        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            // 删除文件并响应
            return $this->deleteFileAndResponse($disk);
        }

        // 获取上传的文件
        $file = $this->file();

        // 获取上传的字段名称
        $ext = $file->getClientOriginalExtension();
        $newName = md5($file->getClientOriginalName().time());
        $basedDir = 'keyword_two/';
        if (in_array($ext, ['jpg','png','jpeg'])) {
            $dir = $basedDir.'images';
        } else {
            $dir = $basedDir.'files';
        }
        $newName = substr($newName, 5, 8).'-'.rand(1111, 99999).'.'.$file->getClientOriginalExtension();

        $result = $disk->putFileAs($dir, $file, $newName);

        $path = "{$dir}/$newName";

        return $result
            ? $this->responseUploaded($path, $disk->url($path))
            : $this->responseErrorMessage('文件上传失败');
    }
}
